<template>
  <CommonPage title="供应商管理" content-row>
    <div class="w-72 pr-4">
      <a-skeleton v-if="dictLoading" active loading :avatar="false"></a-skeleton>
      <a-tree
        v-else-if="dictData.length > 0"
        v-model:selectedKeys="selectedKeys"
        :tree-data="dictData"
        :field-names="{ title: 'label', key: 'value' }"
        block-node
        show-line
        show-icon
        default-expand-all
      >
      </a-tree>
      <SlEmpty v-else />
    </div>
    <div class="flex-1 flex flex-col overflow-hidden">
      <div class="mb-4">
        <a-button type="primary" :disabled="selectedKeys.length === 0" @click="showCreateModal">新增供应商</a-button>
      </div>
      <div class="flex-1 overflow-hidden">
        <SlTable
          class="table-pg-px0"
          :columns="columns"
          row-key="id"
          :data-source="tableData"
          :pagination="pagination"
          :loading="tableLoading"
        >
          <template #bodyCell="{ column, record }">
            <div v-if="column.key === 'oper'">
              <div class="mb-1">
                <a @click="showUpdateModal(record)">编辑</a>
                <a class="ml-2 text-red-400" @click="handleDelete(record)">删除</a>
              </div>
              <div class="mb-1">
                <a @click="showAddressBook(record)">通讯录管理</a>
              </div>
              <div>
                <a @click="showLicenseManage(record)">证照管理</a>
              </div>
            </div>
          </template>
        </SlTable>
      </div>
    </div>
    <CURDDialog
      ref="CURDModalIns"
      id-key="id"
      create-title="新增供应商"
      update-title="编辑供应商"
      delete-message="确认删除该供应商吗？"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :curd="curd"
      :reload-table="reloadTable"
      :get-detail="getDetail"
      :columns="columns"
      @open="handleOpen"
      @before-ok="beforeOk"
    />
    <AddressBookModal v-model:visible="abVisible" :title="abTitle" :supplier-id="curSupplierId" />
    <LicenseManageModal v-model:visible="lmVisible" :title="lmTitle" :supplier-id="curSupplierId" />
  </CommonPage>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useCURD } from "/@/hooks/useCURD";
import { TableProps } from "ant-design-vue";
import { getDictOptions } from "/@/api/main/system";
import { DictTypeCode } from "/@/api/main/system/models";
import {
  CURDAction,
  FormItemComponentType,
  FormItemData,
  ShowCURDModalOptions,
  CURDDialogExpose,
  CURDModalEvent,
} from "/@/components/CURDDialog/models";
import { SupplierItem, CompanyType } from "/@/api/main/pis/models";
import { Api } from "/@/api/main/pis";
import { SelectOptionItem } from "/@/types/antd";
import { enumToOptions, getLabelByValueFromEnum } from "/@/utils/common";
import AddressBookModal from "./AddressBookModal.vue";
import LicenseManageModal from "./LicenseManageModal.vue";
/**
 * 行政区域
 */
const dictData = ref<SelectOptionItem[]>([]);
const selectedKeys = ref<number[]>([]);
const dictLoading = ref(true);
onMounted(async () => {
  const data = await getDictOptions({ typeCode: DictTypeCode.region });
  dictLoading.value = false;
  if (data) {
    dictData.value = data;
    if (data.length > 0) {
      selectedKeys.value = [data[0].value as number];
    }
  }
});
watch(selectedKeys, (keys) => {
  reloadTable({ model: { adminRegionId: keys.length > 0 ? keys[0] : "" } });
});
/**
 * 供应商表格
 */
const columns = ref<TableProps<SupplierItem>["columns"]>([
  {
    title: "统一社会信用编码",
    dataIndex: "uscCode",
  },
  {
    title: "名称",
    dataIndex: "name",
  },
  {
    title: "行政区域",
    dataIndex: "adminRegion",
  },
  {
    title: "办公地址",
    dataIndex: "officeAddress",
  },
  {
    title: "注册地址",
    dataIndex: "registerAddress",
  },
  {
    title: "联系电话",
    dataIndex: "phone",
  },
  {
    title: "邮箱",
    dataIndex: "email",
  },
  {
    title: "传真",
    dataIndex: "fax",
  },
  {
    title: "法人",
    dataIndex: "legalName",
  },
  {
    title: "法人身份证号",
    dataIndex: "legalIdCard",
  },
  {
    title: "银行",
    dataIndex: "bankName",
  },
  {
    title: "结算账号",
    dataIndex: "bankNum",
  },
  {
    title: "企业类型",
    dataIndex: "companyType",
    customRender({ text }) {
      return getLabelByValueFromEnum(text, CompanyType, "companyType");
    },
  },
  {
    title: "操作",
    key: "oper",
    fixed: "right",
    width: 100,
  },
]);

const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<SupplierItem>({
  getPageUrl: Api.supplierPage,
  cudUrl: Api.suppliers,
  loadOnMounted: false,
});
/**
 * 供应商窗
 */
const CURDModalIns = ref<CURDDialogExpose>();
const showOptions = ref<ShowCURDModalOptions>();
const model = ref<Partial<SupplierItem>>({
  uscCode: "",
  name: "",
  mnemonicCode: "",
  adminRegionId: -1,
  officeAddress: "",
  registerAddress: "",
  phone: "",
  email: "",
  fax: "",
  legalName: "",
  legalIdCard: "",
  bankName: "",
  bankNum: "",
  companyType: CompanyType.GeneralTaxpayer,
});
const modelFormSetting = ref<FormItemData[]>([
  {
    key: "uscCode",
    required: true,
  },
  {
    key: "name",
    required: true,
  },
  {
    key: "mnemonicCode",
    label: "助记码",
  },
  {
    key: "adminRegionId",
    type: FormItemComponentType.TREESELECT,
    async getData() {
      return dictData.value;
    },
    props: {},
  },
  {
    key: "officeAddress",
    type: FormItemComponentType.TEXTAREA,
  },
  {
    key: "registerAddress",
    type: FormItemComponentType.TEXTAREA,
  },
  {
    key: "phone",
  },
  {
    key: "email",
  },
  {
    key: "fax",
  },
  {
    key: "legalName",
  },
  {
    key: "legalIdCard",
  },
  {
    key: "bankName",
  },
  {
    key: "bankNum",
  },
  {
    key: "companyType",
    type: FormItemComponentType.SELECT,
    props: {
      options: enumToOptions(CompanyType, "companyType"),
    },
  },
]);
function handleOpen() {
  model.value.adminRegionId = selectedKeys.value[0] || "";
}
function beforeOk() {}
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record) {
  showOptions.value = { action: CURDAction.DELETE, ids: [record.id] };
}
async function getDetail(record) {
  return {};
}
/**
 *
 */
const curSupplierId = ref<number>();

const abVisible = ref(false);
const abTitle = ref("");
function showAddressBook(record) {
  curSupplierId.value = record.id;
  abTitle.value = `供应商(${record.name})通讯录`;
  abVisible.value = true;
}

const lmVisible = ref(false);
const lmTitle = ref("");
function showLicenseManage(record) {
  curSupplierId.value = record.id;
  lmTitle.value = `供应商(${record.name})证照`;
  lmVisible.value = true;
}

watch(abVisible, (v) => {
  if (!v) {
    curSupplierId.value = void 0;
  }
});
watch(lmVisible, (v) => {
  if (!v) {
    curSupplierId.value = void 0;
  }
});
</script>
